<?php
use PhpAmqpLib\Connection\AMQPStreamConnection;

$exchange_name = 'router';
$queue_name = 'msgs';
$consumerTag = 'consumer';

include_once __DIR__.'/config.php';

$connectsion = new AMQPStreamConnection(HOST,PORT,USER,PASS,VHOST);

$channel = $connectsion->channel();

$channel->queue_declare($queue_name,false,true,false,false);

$channel->exchange_declare($exchange_name,AMQP_EX_TYPE_DIRECT,false,true,false);

$channel->queue_bind($queue_name,$exchange_name);

/**
 * @param \PhpAmqpLib\Message\AMQPMessage $message
 */
function process_message($message){

    if($message->body == 'good'){
        echo "成功收到消息，消息内容为：{$message->body}";
        $message->ack();
    }else{
        echo "成功收到消息，消息内容为：{$message->body}";
        echo "将消息打回，重回队列";
        $message->nack(true);
    }

    // Send a message with the string "quit" to cancel the consumer.
    if($message->body == 'quit'){
        $message->getChannel()->basic_cancel($message->getConsumerTag());
    }
}

//执行队列
$channel->basic_consume($queue_name,$consumerTag,false,false,false,false,'process_message');

/**
 * @param \PhpAmqpLib\Channel\AMQPChannel $channel
 * @param \PhpAmqpLib\Connection\AbstractConnection $connection
 */
function shutdown($channel, $connection)
{
    $channel->close();
    $connection->close();
}

//注册关机功能
//register_shutdown_function('shutdown', $channel, $connection);

// Loop as long as the channel has callbacks registered

while ($channel->is_consuming()){
    $channel->wait();
}